package com.ws.mbp.springsecuritydemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许来自 http://localhost:8080 的请求
       // config.addAllowedOrigin("*");  //全部的请求 config.setAllowCredentials(true); 不共存
       config.setAllowedOrigins(Arrays.asList("http://localhost:8080","http://localhost:5173")); // 允许的请求域名，可以设置多个
        // 允许的请求方法，包含 DELETE
        config.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT", "OPTIONS"));
        // 允许的请求头
        config.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
        // 允许携带凭证
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有路径应用 CORS 配置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}